//
//  AppDelegate.swift
//  weibo---练习
//
//  Created by 胡海波 on 15/6/24.
//  Copyright © 2015年 胡海波. All rights reserved.
//

import UIKit
import AFNetworking

var sharedUserAccount = UserAccount.loadAccount()

///  切换根控制器通知
let SwitchRootVCNotification = "SwitchRootVCNotification"

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()

        window?.rootViewController = defaultViewController()

        window?.makeKeyAndVisible()

        setupNetwork()

        setAppearance()

        // 注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "swifchViewController:", name: SwitchRootVCNotification, object: nil)
        
        return true
    }

    ///  切换控制器
    func swifchViewController(n: NSNotification) {

        let isMainVc = n.object as! Bool

        window?.rootViewController = isMainVc ? MainViewController() : WelcomeViewController()

    }

    ///  判断加载的默认控制器
    private func defaultViewController() -> UIViewController {

        // 1.判断用户是否登陆
        if sharedUserAccount != nil {
            // 如果登陆，判断是否有新版本
            return isNewUpdate() ? NewFeatureViewController() : WelcomeViewController()

        }

        return MainViewController()
    }


    // 判断是否是新版本
    private func isNewUpdate() -> Bool {

        // 1.获取应用程序‘当前版本’
        let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        let version = Double(currentVersion)
        // 2.获取应用程序‘之前的版本’，从用户偏好中读取
        let versionKey = "versionKey"
        let sandBoxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(versionKey)
        // 3.将‘当前版本’写入用户偏好
        NSUserDefaults.standardUserDefaults().setDouble(version!, forKey: versionKey)

        return version > sandBoxVersion

    }

    // 设置网络
    private func setupNetwork() {

        // 设置网路指示器
        AFNetworkActivityIndicatorManager.sharedManager().enabled = true
        // 设置网络缓存
        let urlCache = NSURLCache(memoryCapacity: 4 * 1024 * 1024, diskCapacity: 20 * 1024 * 1024, diskPath: nil)
        NSURLCache.setSharedURLCache(urlCache)

    }

    // 设置外观
    private func setAppearance() {

        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        UITabBar.appearance().tintColor = UIColor.orangeColor()
    }

}

